import './index.css';
import {useCallback, useContext, useState} from "react";
import StuContext from "../../store/StuContext";
import StudentForm from "../StudentForm";
import useFetch from "../../hooks/useFetch";

const Student = (props) => {
	const [isEdit, setIsEdit] = useState(false);
	const ctx = useContext(StuContext);
	const {loading, error, fetchData: delStu} = useFetch({
		url: `students/${props.stu.documentId}`,
		method: "DELETE",
	}, ctx.fetchData);

	const deleteHandler = () => {
		delStu();
	}

	// 取消编辑按钮
	const cancelEdit = () => {
		setIsEdit(false);
	}

	const {id, name, gender, age, address} = props.stu;
	return (
		<>

			{!isEdit &&
				<tr>
					<td>{name}</td>
					<td>{gender}</td>
					<td>{age}</td>
					<td>{address}</td>
					<td>
						<button onClick={deleteHandler}>删除</button>
						<button onClick={() => setIsEdit(true)}>修改</button>
					</td>
				</tr>
			}
			{
				isEdit && <StudentForm stu={props.stu} onCancel={cancelEdit} />
			}
			{loading &&
				<tr>
					<td colSpan={5}>正在删除数据..</td>
				</tr>
			}
		</>
	)
}

export default Student;